<?php

namespace App\Http\Controllers\User;

use App\Models\Trade;
use Illuminate\Http\Request;

class BillController extends BaseController
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->assign(['menu'=>'bill']);
    }

    public function index()
    {
        $this->assign([
            'q'=>'',
            'date_range'=>'all',
            'trade_type'=>'all',
            'pay_type'=>'all',
            'wallet'=>$this->user->wallet()->findOrNew($this->uid),
            'trade_status_items'=>trans('mall.buyer_trade_status_items')
        ]);

        $time = 0;
        $seconds = 86400;
        $queryParams = [];
        $date_range = $this->request->get('date_range');
        $date_range = $date_range ? $date_range : 'all';
        if ($date_range == '3days'){
            $time = time() - $seconds*3;
        }elseif ($date_range == '7days'){
            $time = time() - $seconds*7;
        }elseif ($date_range == 'oneMonth'){
            $time = time() - $seconds*30;
        }elseif ($date_range == 'threeMonth'){
            $time = time() - $seconds*90;
        }elseif ($date_range == 'oneYear'){
            $time = time() - $seconds*365;
        }
        $queryParams['date_range'] = $date_range;
        $query = Trade::where(function ($query){
            return $query->where('payer_uid', $this->uid)->orWhere('payee_uid', $this->uid);
        });

        if ($time) {
            $query = $query->where('created_at', '>', $time);
        }

        $trade_type = $this->request->get('trade_type');
        $trade_type = $trade_type ? $trade_type : 'all';
        if ($trade_type != 'all') {
            $queryParams['trade_type'] = $trade_type;
            $query = $query->where('trade_type', strtolower($trade_type));
        }

        $pay_type = $this->request->get('pay_type');
        $pay_type = $pay_type ? $pay_type : 'all';
        if ($pay_type != 'all') {
            $queryParams['pay_type'] = $pay_type;
            $query = $query->where('pay_type', $pay_type);
        }

        $q = $this->request->get('q');
        if ($q) {
            $queryParams['q'] = $q;
            $query = $query->where(function ($query) use ($q){
                return $query->where('subject', 'LIKE', "%$q%")->orWhere('body', 'LIKE', "%$q%");
            });
        }

        $this->assign($queryParams);

        $items = $query->orderByDesc('trade_id')->paginate(20);

        $this->assign([
            'pagination'=>$items->appends($queryParams)->render(),
            'totalCount'=>$items->total(),
            'items'=>$items->map(function ($item){
                $item->income = $item->payee_uid == $this->uid;
                return $item;
            })
        ]);

        return $this->view('user.trade.bill');
    }
}
